package q468_validIPAddress;

public class Solution {
    public static void main(String[] args) {
        String a = "2001:db8:85a3:0::8a2E:0370:7334";
        String[] splits = a.split(":");
        System.out.println(splits.length);
        for (int i = 0; i < splits.length; i++) {
            System.out.println(splits[i].isEmpty());
        }
    }
    public String validIPAddress(String queryIP) {
        if (queryIP.contains(".")) {
            return validIPv4(queryIP);
        } else if (queryIP.contains(":")) {
            return validIPv6(queryIP);
        }
        return "Neither";
    }

    private String validIPv6(String queryIP) {
        if (queryIP.length() > 39) {
            return "Neither";
        }
        String[] strs = queryIP.split(":");
        if (strs.length != 8 || queryIP.charAt(0) == ':' || queryIP.charAt(queryIP.length() - 1) == ':') {
            return "Neither";
        }
        for (String str : strs) {
            if (str.length() > 4 || str.isEmpty()) {
                return "Neither";
            }
            for (int i = 0; i < str.length(); i++) {
                if (!isHex(str.charAt(i))) {
                    return "Neither";
                }
            }
        }
        return "IPv6";
    }

    private boolean isHex(char charAt) {
        return (charAt >= '0' && charAt <= '9') || (charAt >= 'a' && charAt <= 'f') || (charAt >= 'A' && charAt <= 'F');
    }

    private String validIPv4(String queryIP) {
        if (queryIP.length() > 15) {
            return "Neither";
        }
        String[] strs = queryIP.split("\\.");
        if (strs.length != 4 || queryIP.charAt(0) == '.' || queryIP.charAt(queryIP.length() - 1) == '.') {
            return "Neither";
        }
        for (String str : strs) {
            if (str.length() > 1 && str.charAt(0) == '0' || str.length() > 3 || str.isEmpty()) {
                return "Neither";
            }
            int num = 0;
            try {
                num = Integer.parseInt(str);
            } catch (NumberFormatException e) {
                return "Neither";
            }
            if (num < 0 || num > 255) {
                return "Neither";
            }
        }
        return "IPv4";
    }
}
